package com.yicong.ants.ui.video.live

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import com.blankj.utilcode.util.ToastUtils
import com.cchao.simplelib.ui.fragment.BaseStatefulFragment
import com.google.gson.Gson
import com.tencent.live2.V2TXLiveDef
import com.tencent.live2.V2TXLivePlayer
import com.tencent.live2.V2TXLivePlayerObserver
import com.tencent.live2.impl.V2TXLivePlayerImpl
import com.x.livesdk.LiveActivity.Companion.start
import com.x.livesdk.Room
import com.x.livesdk.util.http.DataCallBack
import com.x.livesdk.util.http.HttpUtil
import com.yicong.ants.R
import com.yicong.ants.databinding.LiveItemFragmentBinding
import com.yicong.ants.manager.UserManager

class LiveItemFragment : BaseStatefulFragment<LiveItemFragmentBinding>() {

    private val livePlayer: V2TXLivePlayer by lazy {
        V2TXLivePlayerImpl(context)
    }
    var liveItem: Room? = null
    var onLiveCompletionListener: (() -> Unit)? = null

    override fun getLayoutId() = R.layout.live_item_fragment

    override fun initEventAndData() {
        liveItem = Gson().fromJson(arguments?.get("LiveItem").toString(), Room::class.java)
        initPlayer()
        loadDetail()
        mDataBind.enterBtn.setOnClickListener {
            if (!UserManager.isLogin()) {
                UserManager.routeLogin(context)
                return@setOnClickListener
            }
            start(requireContext(), liveItem!!.live_number, false)
        }
        mDataBind.followBtn.setOnClickListener {
            if (UserManager.notLogin()) {
                UserManager.routeLogin(activity)
                return@setOnClickListener
            }
            HttpUtil.api.follow(liveItem!!.live_number).enqueue(DataCallBack(
                onSuccess = {
                    if (mDataBind.followBtn.text == "已关注") {
                        mDataBind.room?.is_follow = "0"
                        ToastUtils.showLong("已取消关注")
                    } else {
                        mDataBind.room?.is_follow = "1"
                        ToastUtils.showLong("关注成功")
                    }
                    mDataBind.room = mDataBind.room
                },
                onFailure = {}
            ))
        }
    }

    private fun initPlayer() {
        livePlayer.setRenderView(mDataBind.videoView)
        livePlayer.setRenderFillMode(V2TXLiveDef.V2TXLiveFillMode.V2TXLiveFillModeFill)
        livePlayer.setObserver(object : V2TXLivePlayerObserver() {
            override fun onAudioLoading(player: V2TXLivePlayer?, extraInfo: Bundle?) {
                if (mDataBind.completion == false) {
                    mDataBind.loadingIcon.visibility = View.VISIBLE
                }
            }

            override fun onVideoPlaying(player: V2TXLivePlayer?, firstPlay: Boolean, extraInfo: Bundle?) {
                super.onVideoPlaying(player, firstPlay, extraInfo)
                mDataBind.loadingIcon.visibility = View.GONE
                mDataBind.loadingBg.visibility = View.GONE
            }

        })
    }

    private fun liveCompletion() {
        mDataBind.loadingBg.visibility = View.VISIBLE
        mDataBind.completion = true
    }

    override fun onLoadData() {
    }

    fun play() {
        loadDetail()
        selected = true
    }

    override fun onResume() {
        super.onResume()
        view?.postDelayed({
            if (selected) {
                livePlayer.startLivePlay(liveItem?.LiveUrl)
            }
        }, 1)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            view?.postDelayed({
                livePlayer.stopPlay()
            }, 1)
        } else {
            view?.postDelayed({
                if (selected) {
                    livePlayer.startLivePlay(liveItem?.LiveUrl)
                }
            }, 1)
        }
    }

    override fun onPause() {
        super.onPause()
        view?.postDelayed({
            livePlayer.stopPlay()
        }, 1)
    }

    private fun loadDetail() {
        if (liveItem == null) {
            return
        }
        HttpUtil.api.loadRoom(liveItem!!.live_number)
            .enqueue(DataCallBack(
                onSuccess = { room ->
                    mDataBind.room = room
                    if (room.status != Room.STATE_LIVE_ING) {
                        liveCompletion()
                    }
                },
                onFailure = {

                }
            ))
    }

    companion object {
        fun create(liveItem: Room): LiveItemFragment {
            val fragment = LiveItemFragment()
            fragment.arguments = bundleOf(Pair<String, String>("LiveItem", Gson().toJson(liveItem)))
            return fragment
        }
    }

    var selected = false
    fun unselected() {
        view?.postDelayed({
            livePlayer.stopPlay()
        }, 1)
        selected = false
    }

    fun isCompletion(): Boolean {
        return mDataBind.completion == true
    }
}